package org.hospital.controller;

import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.hospital.entity.Employee;
import org.hospital.entity.Log;
import org.hospital.entity.Permission;
import org.hospital.entity.Position;
import org.hospital.service.LogService;
import org.hospital.service.PermissionService;
import org.hospital.util.Constant;
import org.hospital.util.DateUtil;
import org.hospital.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("permissionController")
@SessionAttributes(value = "employee", types = Employee.class)
public class PermissionController {

	@Autowired
	private PermissionService pmService;
	@Autowired
	private LogService lService;

	/**
	 * 添加职位
	 * 
	 * @param req
	 *            {name,rank,?description,permissionIds:[]}
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/createPosition", produces = "text/json;charset=utf-8")
	public String createPosition(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_POSITION.getName(), 5)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		// 获取数据
		String name = req.getParameter("name");
		int rank = Integer.parseInt(req.getParameter("rank"), 10);
		JSONArray pmJA = JSON.parseArray(req.getParameter("permissionIds"));
		String description = req.getParameter("description");

		// 检测数据合法性
		List<Permission> pmList = pmService.getPermissionByPosition(operator.getPositionId());
		for (int i = 0; i < pmJA.size(); i++) {
			boolean isHave = false;
			for (int j = 0; j < pmList.size(); j++) {
				if (pmList.get(j).getPermissionId().equals(pmJA.getInteger(i))) {
					isHave = true;
				}
			}
			if (!isHave) {
				return StringUtil.setResult(402, "权限不足,存在自身没有的权限", "");
			}
		}

		// 数据库操作
		Position ps = new Position();
		ps.setCreatorId(operator.getEmployeeId());
		ps.setName(name);
		ps.setRank(rank);
		ps.setCreateTime(new Timestamp(DateUtil.getNowLong()));
		if (null != description && description.length() != 0) {
			ps.setDescription(description);
		}

		if (!pmService.createPosition(ps, pmJA)) {
			return StringUtil.setResult(501, "数据库操作失败", "");
		}

		Log log = new Log();
		log.setEmployeeId(operator.getEmployeeId());
		log.setContent(JSON.toJSONString(ps));
		log.setOperate(Constant.CREATE_POSITION.getName());
		log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
		lService.addEntity(log);

		return StringUtil.setResult(200, "创建成功", "");
	}

	/**
	 * 修改职位 具有创建职位权限的管理员
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/alterPosition", produces = "text/json;charset=utf-8")
	public String alterPosition(WebRequest req, HttpSession session) {
		// 验证权限
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		if (!pmService.isPermisionEnough(operator.getPositionId(),
				Constant.CREATE_POSITION.getName(), 5)) {
			return StringUtil.setResult(402, "权限不足", "");
		}

		// 获取数据
		try {
			int positionId = Integer.parseInt(req.getParameter("positionId"), 10);
			String name = req.getParameter("name");
			int rank = Integer.parseInt(req.getParameter("rank"), 10);
			JSONArray pmJA = JSON.parseArray(req.getParameter("permissionIds"));
			String description = req.getParameter("description");
			// System.out.println("alterPosition.rank : " + rank);
			// 检测数据合法性
			// 检测是否设置了自身不具备的权限
			List<Permission> pmList = pmService.getPermissionByPosition(operator.getPositionId());
			for (int i = 0; i < pmJA.size(); i++) {
				boolean isHave = false;
				for (int j = 0; j < pmList.size(); j++) {
					if (pmList.get(j).getPermissionId().equals(pmJA.getInteger(i))) {
						isHave = true;
					}
				}
				if (!isHave) {
					// System.out.println("controller.alterPosition.permissionId : "+pmJA.getInteger(i));
					return StringUtil.setResult(402, "权限不足,存在自身没有的权限", "");
				}
			}

			// 数据库操作
			Position ps = new Position();
			ps.setPositionId(positionId);
			ps.setName(name);
			ps.setRank(rank);
			ps.setCreateTime(new Timestamp(DateUtil.getNowLong()));
			if (null != description && description.length() != 0) {
				ps.setDescription(description);
			}

			System.out.println("html.alterPosition.dbPosition : " + JSON.toJSONString(ps, true));
			if (!pmService.alterPosition(ps, pmJA)) {
				return StringUtil.setResult(501, "数据库操作失败", "");
			}

			Log log = new Log();
			log.setEmployeeId(operator.getEmployeeId());
			log.setContent(JSON.toJSONString(ps));
			log.setOperate(Constant.ALTER_POSITION.getName());
			log.setOperateTime(new Timestamp(DateUtil.getNowLong()));
			lService.addEntity(log);

			return StringUtil.setResult(200, "操作成功", "");
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}

	}

	/**
	 * 获取 所有职位信息
	 * 
	 * @param req
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getAllPosition", produces = "text/json;charset=utf-8")
	public String getAllPosition(WebRequest req, HttpSession session) {
		// [{positionId,creatorId,creatorName,rank,description,name,createTime}]
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		JSONArray resultJA = pmService.getAllPosition();
		if (resultJA == null || resultJA.size() == 0) {
			return StringUtil.setResult(414, "数据为空", "");
		}

		return StringUtil.setResult(200, "操作成功", resultJA);
	}

	/**
	 * 获取指定职位的权限
	 * 
	 * @param req
	 * @return [1,2,3,5,...]
	 */
	@ResponseBody
	@RequestMapping(value = "/getPermissionByPositionId", produces = "text/json;charset=utf-8")
	public String getPermissionByPositionId(WebRequest req, HttpSession session) {
		// [{positionId,creatorId,creatorName,rank,description,name,createTime}]
		Employee operator = (Employee) session.getAttribute("employee");
		if (operator == null) {
			return StringUtil.setResult(405, "请重新登陆", "");
		}
		JSONArray resultJA = pmService.getPermissionByPositionId(operator.getPositionId());
		if (resultJA == null || resultJA.size() == 0) {
			return StringUtil.setResult(414, "数据为空", "");
		}
		return StringUtil.setResult(200, "操作成功", resultJA);

	}

	@ResponseBody
	@RequestMapping(value = "/isPermissionEnough", produces = "text/json;charset=utf-8")
	public String isPermissionEnough(WebRequest req, HttpSession session) {

		try {
			int positionId = Integer.parseInt(req.getParameter("positionId"), 10);
			String permission = req.getParameter("permission");
			int rank = Integer.parseInt(req.getParameter("rank"), 10);
			JSONObject resultJO = new JSONObject();
			resultJO.put("isEnough", pmService.isPermisionEnough(positionId, permission, rank));
			return StringUtil.setResult(200, "操作成功", resultJO);
		} catch (Exception e) {
			e.printStackTrace();
			return StringUtil.setResult(403, "参数格式有误", "");
		}
	}
}
